<template>
  <div class="login-container">
    <el-row>
      <el-col :span="12" :xs="0"></el-col>
      <el-col :span="12" :xs="24">
        <el-form class="login-form" :model="loginForm" :rules="rules" ref="loginFormRef">
          <h1>通用后台管理系统</h1>
          <h2>欢迎使用vue3-admin</h2>
          <el-form-item class="login-item" prop="username">
            <el-input
              :prefix-icon="User"
              v-model="loginForm.username"
              placeholder="请输入用户名"
            ></el-input>
          </el-form-item>
          <el-form-item class="login-item" prop="password">
            <el-input
              type="password"
              :prefix-icon="Lock"
              v-model="loginForm.password"
              placeholder="请输入密码"
              show-password
            ></el-input>
          </el-form-item>
          <el-form-item class="login-item">
            <el-button
              type="primary"
              :loading="loading"
              class="login_btn"
              size="default"
              @click="handleLogin"
            >
              登录
            </el-button>
          </el-form-item>
          <div class="info">
            <el-checkbox v-model="remember">记住我</el-checkbox>
            <el-link href="#">忘记密码</el-link>
          </div>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { User, Lock } from '@element-plus/icons-vue'
import useUserStore from '@/store/modules/user'
import { useRouter, useRoute } from 'vue-router'
import { ElNotification } from 'element-plus'
import { getTime } from '@/utils/time'

//获取路由器对象
let $router = useRouter()
//获取当前路由对象
let $route = useRoute()
//定义变量用于控制登录按钮的加载效果
const loading = ref(false)

const remember = ref(false)
const useStore = useUserStore()

let loginForm = reactive({
  username: 'admin',
  password: '111111',
})

//自定义校验规则函数
const validatorUserName = (rule: any, value: string, callback: any) => {
  //rule:数组校验规则对象，
  //value: 表单元素的文本内容
  //callback: 校验完成后的回调函数，如果符合条件放行通过，否则注入错误提示信息

  //可以根据需求，编写正则表达式
  // if (/^\d{5,10}$/.test(value)) {
  //   callback()
  // }else {
  //   callback(new Error('用户名长度在3到10个字符'))
  // }

  if (value.length < 3 || value.length > 10) {
    callback(new Error('用户名长度在3到10个字符'))
  } else {
    callback()
  }
}

//表单校验规则
const rules = {
  username: [
    //{ required: true, min: 3, max: 10, message: '用户名长度在3到10个字符', trigger: 'change' },
    //自定义校验规则
    {
      trigger: 'change',
      validator: validatorUserName,
    },
  ],
  password: [
    { required: true, min: 6, max: 16, message: '密码长度在6到16个字符', trigger: 'change' },
  ],
}

//获取el-form表单组件
const loginFormRef = ref()

const handleLogin = async () => {
  //保证全部表单校验通过后才会发送请求
  await loginFormRef.value.validate()

  //开启登录按钮的加载效果
  loading.value = true

  try {
    //保证登录成功
    await useStore.userLogin(loginForm)
    //编程式导航跳转到首页，判断登录路由是否有query参数，有的话就带上参数
    let redirect: any = $route.query.redirect
    $router.push({ path: redirect || '/' })

    //登录成功提示信息
    ElNotification({
      title: `Hi,${getTime()}好！`,
      message: '欢迎使用系统',
      type: 'success',
    })
    //登录成功后清空登录加载效果
    loading.value = false
  } catch (error) {
    console.log(error)
    ElNotification({
      title: '登录失败',
      message: (error as Error).message,
      type: 'error',
    })
    //登录失败后清空登录加载效果
    loading.value = false
  }
}
</script>

<style scoped lang="scss">
.login-container {
  top: 30%;
  width: 100%;
  height: 100vh;
  padding: 40px;
  font-size: 18px;
  color: white;
  background: url('@/assets/images/login-bg.jpg') no-repeat center center;
  background-size: cover;
  .login-form {
    position: relative;
    top: 50%;
    width: 100%;
    height: 50vh;
    background: url('@/assets/images/login-form.png') no-repeat center center;
    background-size: cover;
    .login-item {
      width: 60%;
      padding: 20px;
      margin: 0 auto;
    }
    h1 {
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 40px;
      color: white;
    }
    h2 {
      display: flex;
      align-items: center;
      justify-content: center;
      margin: 20px 0;
      font-size: 25px;
      color: white;
    }
    .login_btn {
      width: 100%;
    }
    .info {
      display: flex;
      align-items: center;
      justify-content: space-around;
      width: 100%;
      color: white;
      .el-checkbox {
        margin-left: 10px;
        color: white;
      }
      .el-link {
        margin-right: 10px;
        color: white;
      }
    }
  }
}
</style>
